//
//  KFGoodsCell.m
//  KafeeSale
//
//  Created by Liboom on 2025/6/9.
//

#import "KFGoodsCell.h"
#import "KFSpecMakeView.h"
@interface KFGoodsCell()<UITextFieldDelegate>
@property(nonatomic, strong) UILabel *nameLab;
@property(nonatomic, strong) UIImageView *goodImageView;
@property(nonatomic, strong) UILabel *priceLab;
@property(nonatomic, strong) UIButton *addBtn;
@property(nonatomic, strong) UIButton *minusBtn;
@property(nonatomic, strong) UIButton *specBtn;
@property(nonatomic, strong) UILabel *numLab;
@property(nonatomic, strong) UILabel *badgeLabel;
@property(nonatomic, strong) UIButton *remarkBtn;
@property(nonatomic, strong) UITextField *remarkTF;
@property(nonatomic, strong) UIView *quantityContainer;
@end
@implementation KFGoodsCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.contentView.backgroundColor = UIColor.whiteColor;
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self createCusUI];
    }
    return self;
}
-(void)createCusUI{
    UIView*bgView = [UIView new];
    bgView.backgroundColor = UIColor.whiteColor;
    bgView.cornerRadius = 10;
    [self.contentView addSubview:bgView];
    bgView.sd_layout.leftSpaceToView(self.contentView, 10).rightSpaceToView(self.contentView, 10).topSpaceToView(self.contentView, 10);
    
//    self.goodImageView = [UIImageView new];
//    self.goodImageView.cornerRadius = 10;
//    [bgView addSubview:self.goodImageView];
//    self.goodImageView.sd_layout.rightSpaceToView(bgView, 10).topSpaceToView(bgView, 10).widthIs(80).heightIs(80);
    
    self.nameLab = [UILabel labelWithTitle:@"" color:UIColor.blackColor fontSize:20];
    self.nameLab.textAlignment = NSTextAlignmentLeft;
    [bgView addSubview:self.nameLab];
    self.nameLab.sd_layout.leftSpaceToView(bgView, 10).topSpaceToView(bgView, 10).rightSpaceToView(bgView, 10).heightIs(20);
    
    self.priceLab = [UILabel labelWithTitle:@"" color:RED_COLOR fontSize:17];
    self.priceLab.font = [UIFont boldSystemFontOfSize:17];
    [bgView addSubview:self.priceLab];
    self.priceLab.sd_layout.leftEqualToView(self.nameLab).topSpaceToView(self.nameLab, 10).heightIs(20);
    [self.priceLab setSingleLineAutoResizeWithMaxWidth:300];
    
    // 添加规格按钮
    self.specBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.specBtn.backgroundColor = [UIColor systemBlueColor];
    [self.specBtn setTitle:@"选规格" forState:UIControlStateNormal];
    [self.specBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.specBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    self.specBtn.layer.cornerRadius = 15;
    [self.specBtn addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:self.specBtn];
    self.specBtn.sd_layout.rightSpaceToView(bgView, 10).centerYEqualToView(bgView).widthIs(60).heightIs(30);

    // 数量角标
    self.badgeLabel = [UILabel labelWithTitle:@"" color:UIColor.whiteColor fontSize:10];
    self.badgeLabel.backgroundColor = [UIColor redColor];
    self.badgeLabel.textAlignment = NSTextAlignmentCenter;
    self.badgeLabel.layer.cornerRadius = 8;
    self.badgeLabel.layer.masksToBounds = YES;
    self.badgeLabel.hidden = YES;
    [self.specBtn addSubview:self.badgeLabel];
    self.badgeLabel.sd_layout.topSpaceToView(self.specBtn, -5).rightSpaceToView(self.specBtn, -5).widthIs(16).heightIs(16);

    // 加减按钮容器（用于没有规格的情况）
    self.quantityContainer = [[UIView alloc] init];
    [bgView addSubview:self.quantityContainer];
    self.quantityContainer.sd_layout.rightSpaceToView(bgView, 10).centerYEqualToView(bgView).widthIs(100).heightIs(30);

    self.addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.addBtn.backgroundColor = [UIColor whiteColor];
    [self.addBtn addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.addBtn setImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
    [self.quantityContainer addSubview:self.addBtn];
    self.addBtn.sd_layout.rightSpaceToView(self.quantityContainer, 0).centerYEqualToView(self.quantityContainer).widthIs(30).heightEqualToWidth();

    self.numLab = [UILabel labelWithTitle:@"" color:UIColor.blackColor fontSize:14];
    self.numLab.hidden = YES;
    self.numLab.textAlignment = NSTextAlignmentCenter;
    [self.quantityContainer addSubview:self.numLab];
    self.numLab.sd_layout.rightSpaceToView(self.addBtn, 0).centerYEqualToView(self.addBtn).widthIs(40).heightIs(20);

    self.minusBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.minusBtn.backgroundColor = [UIColor whiteColor];
    self.minusBtn.hidden = YES;
    [self.minusBtn addTarget:self action:@selector(minusBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.minusBtn setImage:[UIImage imageNamed:@"minus"] forState:UIControlStateNormal];
    [self.quantityContainer addSubview:self.minusBtn];
    self.minusBtn.sd_layout.rightSpaceToView(self.numLab, 0).centerYEqualToView(self.numLab).widthIs(30).heightEqualToWidth();

    // 默认隐藏规格按钮，显示加减按钮容器
    self.specBtn.hidden = YES;
    
    [bgView setupAutoHeightWithBottomView:self.priceLab bottomMargin:10];
    [self setupAutoHeightWithBottomView:bgView bottomMargin:10];
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
    self.model.localRemark = textField.text;
}
-(void)addBtnClick{
    if (self.model.cooksList.count >0 || self.model.specList.count > 0) {
        // 确保传入的model包含当前的选中状态
        KFSpecMakeView *specView = [[KFSpecMakeView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) model:self.model];
        specView.confirmBlock = ^(NSInteger quantity, NSArray *selectedSpecs, NSArray *selectedPractices, NSArray *selectedBeans, NSArray *practiceTitles) {
            NSLog(@"数量: %ld", quantity);
            NSLog(@"规格: %@", selectedSpecs);
            NSLog(@"做法: %@", selectedPractices);
            NSLog(@"豆子: %@", selectedBeans);
            
            VicSingleObject *single = [VicSingleObject getInstance];
            
            // 创建新的商品实例（不同规格作为不同商品）
            KFProductModel *mo = [[KFProductModel alloc] init];
            mo.tid = self.model.tid;
            mo.name = self.model.name;
            mo.price = self.model.price;
            mo.choseCount = quantity;
            mo.localRemark = self.model.localRemark;
            mo.remark = self.model.remark;
            mo.bean = self.model.bean;
            mo.specList = self.model.specList;
            mo.cooksList = self.model.cooksList;
            mo.selectedSpecs = selectedSpecs;
            mo.selectedPractices = selectedPractices;
            mo.selectedBeans = selectedBeans;
            mo.practiceTitles = practiceTitles;
            
            // 直接添加到购物车
            [single.cartList addObject:mo];
            
            // 更新当前cell的显示数量（累加所有相同商品的数量）
            NSInteger totalCount = 0;
            for (KFProductModel *cartMo in single.cartList) {
                if ([cartMo.tid isEqualToString:self.model.tid]) {
                    totalCount += cartMo.choseCount;
                }
            }
            self.model.choseCount = totalCount;
            self.numLab.text = [@(totalCount) stringValue];
            
            // 更新角标
            if (totalCount > 0) {
                self.badgeLabel.hidden = NO;
                self.badgeLabel.text = [NSString stringWithFormat:@"%ld", totalCount];
            } else {
                self.badgeLabel.hidden = YES;
            }
            
            // 更新UI
            self.minusBtn.hidden = NO;
            self.numLab.hidden = NO;
            self.remarkBtn.hidden = NO;
            if (self.actionBtnBlock) {
                self.actionBtnBlock(self.numLab.text);
            }
        };
        specView.closeBlock = ^{
            NSLog(@"关闭规格选择");
        };
        [specView showInView:[Mytools currentViewController].view];
    } else {
        // 没有规格和做法的处理逻辑
        VicSingleObject * single = [VicSingleObject getInstance];
        BOOL isFind = NO;
        for (KFProductModel * mo in single.cartList) {
            if([mo.tid isEqualToString:self.model.tid]){
                mo.choseCount += 1; // 直接加1
                isFind = YES;
                break;
            }
        }
        if (!isFind) {
            self.model.choseCount = 1;
            // 创建副本添加到购物车
            KFProductModel *cartCopy = [[KFProductModel alloc] init];
            cartCopy.tid = self.model.tid;
            cartCopy.name = self.model.name;
            cartCopy.price = self.model.price;
            cartCopy.choseCount = 1;
            cartCopy.localRemark = self.model.localRemark;
            [single.cartList addObject:cartCopy];
        } else {
            self.model.choseCount += 1;
        }
        
        self.numLab.text = [@(self.model.choseCount) stringValue];
        
        self.minusBtn.hidden = NO;
        self.numLab.hidden = NO;
        self.remarkBtn.hidden = NO;
        if (self.actionBtnBlock) {
            self.actionBtnBlock(self.numLab.text);
        }
    }
}
- (BOOL)isSameProduct:(KFProductModel *)model1 with:(KFProductModel *)model2 {
    if (![model1.tid isEqualToString:model2.tid]) {
        return NO;
    }
    
    // 比较规格
    if (model1.selectedSpecs.count != model2.selectedSpecs.count) {
        return NO;
    }
    
    for (int i = 0; i < model1.selectedSpecs.count; i++) {
        KFDishSpecList *spec1 = model1.selectedSpecs[i];
        KFDishSpecList *spec2 = model2.selectedSpecs[i];
        if (![spec1.specName isEqualToString:spec2.specName] || spec1.specPrice != spec2.specPrice) {
            return NO;
        }
    }
    
    // 比较做法
    if (model1.selectedPractices.count != model2.selectedPractices.count) {
        return NO;
    }
    
    for (int i = 0; i < model1.selectedPractices.count; i++) {
        NSDictionary *practice1 = model1.selectedPractices[i];
        NSDictionary *practice2 = model2.selectedPractices[i];
        if (![practice1[@"cookName"] isEqualToString:practice2[@"cookName"]] ||
            [practice1[@"cookPrice"] floatValue] != [practice2[@"cookPrice"] floatValue]) {
            return NO;
        }
    }
    
    // 比较豆子
    if (![model1.selectedBeans isEqualToArray:model2.selectedBeans]) {
        return NO;
    }
    
    return YES;
}
-(void)minusBtnClick{
    VicSingleObject *single = [VicSingleObject getInstance];
    
    // 从购物车中移除该商品的所有实例
    NSMutableArray *productsToRemove = [NSMutableArray array];
    for (KFProductModel *mo in single.cartList) {
        if([mo.tid isEqualToString:self.model.tid]){
            [productsToRemove addObject:mo];
        }
    }
    [single.cartList removeObjectsInArray:productsToRemove];
    
    // 重置当前商品的数量和选择
    self.model.choseCount = 0;
    self.model.selectedSpecs = @[];
    self.model.selectedPractices = @[];
    self.model.selectedBeans = @[];
    
    self.numLab.text = @"0";
    self.numLab.hidden = YES;
    self.minusBtn.hidden = YES;
    self.badgeLabel.hidden = YES;
    
    if (self.actionBtnBlock) {
        self.actionBtnBlock(self.numLab.text);
    }
}
-(void)addRemarkClick{
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"请输入备注内容" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        NSArray * textfields = alert.textFields;
        UITextField * tf = textfields[0];
        self.model.localRemark = tf.text;
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        DLLog(@"cancel");
    }]];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
//        textField.placeholder = @"这里输入内容"; // 占位文字
        textField.clearButtonMode = UITextFieldViewModeWhileEditing; // 清空按
    }];
    [[Mytools currentViewController] presentViewController:alert animated:YES completion:nil];
}
- (void)setModel:(KFProductModel *)model{
    _model = model;
    self.nameLab.text = model.name;
    self.priceLab.text = [NSString stringWithFormat:@"￥%.0lf",model.price];
    self.numLab.text = [NSString stringWithFormat:@"%ld",model.choseCount];
    self.remarkTF.text = model.localRemark;
    
    // 根据是否有规格做法显示不同的按钮
    BOOL hasSpecs = model.cooksList.count > 0 || model.specList.count > 0;
    
    if (hasSpecs) {
        // 有规格做法：显示规格按钮，隐藏加减按钮
        self.specBtn.hidden = NO;
        self.quantityContainer.hidden = YES;
        
        // 更新角标
        if (model.choseCount > 0) {
            self.badgeLabel.hidden = NO;
            self.badgeLabel.text = [NSString stringWithFormat:@"%ld", model.choseCount];
        } else {
            self.badgeLabel.hidden = YES;
        }
    } else {
        // 无规格做法：显示加减按钮，隐藏规格按钮
        self.specBtn.hidden = YES;
        self.quantityContainer.hidden = NO;
        
        // 更新加减按钮状态
        self.minusBtn.hidden = model.choseCount == 0;
        self.numLab.hidden = model.choseCount == 0;
    }
}
@end
